package rpc.trace;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import rpc.core.RpcData;

/*********
 *
 *
 *@author 197
 *@date 2020/6/23 10:07
 *
 **/
public class TraceContext {

  private static final String RANDOM =
      RandomStringUtils.randomAlphabetic(5) + "-" + RandomStringUtils.randomAlphabetic(5)
          .toLowerCase();
  private static final AtomicLong TRACE_ATOMIC_LONG = new AtomicLong(1);
  private static final AtomicLong SPAN_ATOMIC_LONG = new AtomicLong(1);
  private String traceId;
  private Multimap<String, Object> contextMap = ArrayListMultimap.create();
  private Multimap<String, Object> logMap = ArrayListMultimap.create();

  public TraceContext() {
//    System.out.println("init " + this);
  }

  public static String getSpanId() {
    return RpcData.getAppName() + "-" + RANDOM + "-" + SPAN_ATOMIC_LONG.getAndIncrement();
  }

  public String getTraceId() {
    if (StringUtils.isBlank(traceId)) {
      traceId = RpcData.getAppName() + "-" + RANDOM + "-" + TRACE_ATOMIC_LONG.getAndIncrement();
    }
    return traceId;
  }

  public void setTraceId(String traceId) {
    this.traceId = traceId;
  }

  public TraceContext clearContextMap() {
    this.contextMap.clear();
    this.contextMap = null;
    return this;
  }

  public TraceContext setContextMapValue(String key, Objects value) {
    if (Objects.isNull(this.contextMap)) {
      this.contextMap = ArrayListMultimap.create();
    }
    this.contextMap.put(key, value);
    return this;
  }

  public TraceContext setLogValue(String key, Object value) {
    if (Objects.isNull(this.logMap)) {
      this.logMap = ArrayListMultimap.create();
    }
    this.logMap.put(key, value);
    return this;
  }
}